package system_smtp_service

import (
	"strings"

	"gitee.com/Luna-CY/Golang-Project-Template/internal/context"
	"gitee.com/Luna-CY/Golang-Project-Template/internal/errors"
	"gitee.com/Luna-CY/Golang-Project-Template/internal/interface/service"
	"gitee.com/Luna-CY/Golang-Project-Template/internal/logger"
	"gitee.com/Luna-CY/Golang-Project-Template/internal/util/pointer"
	"gitee.com/Luna-CY/Golang-Project-Template/model"
	gonanoid "github.com/matoous/go-nanoid"
)

func (cls *Smtp) LogTimeTo(ctx context.Context, to []string, subject string, bodyType model.SystemSmtpLogBodyType, body string, attachments []*model.SystemObject, sendTime int64, fields ...service.SystemSmtpLogField) errors.Error {
	if 0 == len(to) {
		logger.SugarLogger(logger.WithRequestId(ctx), logger.WithStack()).Errorf("ISS_TP.S_TP.LTT_TO.134455 to is %d", len(to))

		return errors.ErrorServerInternalError("ISS_TP.S_TP.LTT_TO.154506", "异常的传入参数")
	}

	var log = new(model.SystemSmtpLog)

	log.Id = gonanoid.MustID(64)
	log.SendType = pointer.New(model.SystemSmtpLogSendTypeTime)
	log.SendTime = pointer.New(sendTime)
	log.To = pointer.New(strings.Join(to, ","))
	log.Subject = pointer.New(subject)
	log.BodyType = pointer.New(bodyType)
	log.Body = pointer.New(body)

	for _, field := range fields {
		if err := field(log); nil != err {
			return err.Relation(errors.ErrorServerInternalError("ISS_TP.S_TP.LTT_TO.342638", "应用选项失败"))
		}
	}

	if err := cls.WithTransaction(ctx, func(ctx context.Context) errors.Error {
		if err := cls.smtpLog.SaveSystemSmtpLog(ctx, log); nil != err {
			return err.Relation(errors.ErrorServerInternalError("ISS_TP.S_TP.LTT_TO.354616", "保存邮件日志失败"))
		}

		for _, item := range attachments {
			var attachment = new(model.SystemSmtpLogAttachment)

			attachment.Id = gonanoid.MustID(64)
			attachment.SmtpLogId = pointer.New(log.Id)
			attachment.ObjectId = pointer.New(item.Id)

			if err := cls.smtpLogAttachment.SaveSystemSmtpLogAttachment(ctx, attachment); nil != err {
				return err.Relation(errors.ErrorServerInternalError("ISS_TP.S_TP.LTT_TO.454649", "保存邮件日志附件失败"))
			}
		}

		return nil
	}); nil != err {
		return err
	}

	return nil
}
